//
//  KLSettingViewController.m
//  blanket
//
//  Created by Mac on 2017/12/4.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "TMGEditPersonInfoViewController.h"
#import "STPhotoUrlImageBrowerController.h"
@interface TMGEditPersonInfoViewController ()<STPhotoUrlImageBrowerControllerDelegate,STActionSheetDelegate>
@property(nonatomic, strong) NSArray  <STTableEasyModel*>                   *dataSouce;
@property(nonatomic, strong) STButton                     *iconButton;
@property(nonatomic, strong) STPhotoUrlImageBrowerController                     *pickerVC;
@property(nonatomic, strong) STUrlPhotoModel                     *urlModel;

@end

@implementation TMGEditPersonInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"编辑资料";
    [self configSubView];
    [self reloadData];
    // Do any additional setup after loading the view.
}
#pragma mark --subView
- (void)configSubView{
    __weak typeof(self) weakSelf =  self;
    self.iconButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)
                                                title:nil
                                           titleColor:nil
                                            titleFont:0
                                         cornerRadius:20
                                      backgroundColor:nil
                                      backgroundImage:[UIImage imageNamed:@"4"]
                                                image:nil];
    [self.iconButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedIconCell];
    }];
    [self.iconButton sd_setBackgroundImageWithURL:[NSURL URLWithString:self.userModel.head] forState:UIControlStateNormal];
}

- (void)reloadData{
    
    NSString * gender;
    if (self.userModel.gender.integerValue == 1) {
        gender = @"男";
    }else if (self.userModel.gender.integerValue == 0){
        gender = @"女";
    }else{
        gender = @"";
    }
    NSString * area = [NSString stringWithFormat:@"%@%@",
                       self.userModel.province.length?self.userModel.province:@"",
                       self.userModel.city.length?self.userModel.city:@""];
    NSArray * sectionOne = @[
                             [[STTableEasyModel alloc] initWithTextString:@"头像" accessoryView:self.iconButton],
                             [[STTableEasyModel alloc] initWithTextString:@"昵称" detailString:self.userModel.nickname],
                             [[STTableEasyModel alloc] initWithTextString:@"性别" detailString:gender],
                             [[STTableEasyModel alloc] initWithTextString:@"地区" detailString:area]];
    
    
    self.dataSouce = sectionOne;
    [self.tableView reloadData];
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 24;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
        
    }
    cell.textLabel.textColor = UIColorFromRGBA(0x333333);
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
    cell.detailTextLabel.textColor = UIColorFromRGBA(0x999999);
    
    STTableEasyModel * model = self.dataSouce[indexPath.row];
    cell.textLabel.text = model.textString;
    cell.detailTextLabel.text = model.detailString;
    if (model.accessoryView) {
        cell.accessoryView = model.accessoryView;
    }else{
        cell.accessoryType = model.accessoryType;
    }
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    STTableEasyModel * model = self.dataSouce[indexPath.row];
    if (indexPath.row == 0) {
        [self onSelectedIconCell];
    }
    if (indexPath.row == 1) {
        [self onSelectedNickNameCellWithIndexPath:indexPath model:model];
    }
    if (indexPath.row == 2) {
        [self onSelectedGenderCellWithIndexPath:indexPath model:model];
    }
    if (indexPath.row == 3) {
        [self onSelectedAreaCellWithIndexPath:indexPath model:model];
    }
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
- (void)onSelectedIconCell{
    if (self.userModel.head.length) {
        STUrlPhotoModel * model = [STUrlPhotoModel new];
        model.thumbImage = self.iconButton.currentBackgroundImage;
        self.pickerVC = [[STPhotoUrlImageBrowerController alloc] initWithArray:@[model] curentIndex:0];
        self.pickerVC.STPhotoUrlImageBrowerControllerdelegate = self;
        self.pickerVC.themeColor = TM_orangeColor;
        self.urlModel = model;
        [self presentViewController:self.pickerVC animated:NO completion:nil];
    }else{
        __weak typeof(self) weakSelf =  self;
        [self showDefultImagePicker:^(UIImage *image) {
            [weakSelf sendIconChangeRequestWithImage:image];
        }];
    }

}
- (void)onSelectedNickNameCellWithIndexPath:(NSIndexPath*)indexPath model:(STTableEasyModel*)model{
    NSString * placeHolder = [NSString stringWithFormat:@"请输入%@",model.textString];
    STTableViewDetailController * detail =
    [[STTableViewDetailController alloc] initWithPlaceholder:placeHolder
                                                       title:model.textString
                                                        text:model.detailString
                                                      handle:^(NSString *text) {
                                                          if (text.length && ![text isEqualToString:model.detailString]) {
                                                              [self sendInfoChangeRequestWithName:text indexPath:indexPath];

                                                          }
                                                          if (!text.length) {
                                                              [SVProgressHUD showErrorWithStatus:@"姓名不能为空"];
                                                          }
                                                          [self.navigationController popViewControllerAnimated:YES];
                                                      }];
    detail.detailLabel.text = @"";
    detail.isShowTextNum = NO;
    [self.navigationController pushViewController:detail animated:YES];
}
- (void)onSelectedGenderCellWithIndexPath:(NSIndexPath*)indexPath model:(STTableEasyModel*)model{
    NSArray * genders = @[@"男",@"女",@"取消"];
    [self showActionSheet:genders andWithBlock:^(int tag) {
        if (tag != 2) {
          [self sendInfoChangeRequestWithGender:genders[tag] indexPath:indexPath];
        }
        
    }];
}
- (void)onSelectedAreaCellWithIndexPath:(NSIndexPath*)indexPath model:(STTableEasyModel*)model{
    STPickerViewController * picker = [[STPickerViewController alloc] initWithDefualtAreaPickerWithHandle:^(NSString *finshString, NSString *area, NSString *city, NSString *provence) {
        [self sendInfoChangeRequestWithProvince:provence city:city indexPath:indexPath];
    }];
    [self.navigationController presentViewController:picker animated:NO completion:nil];
}
#pragma mark --STPhotoUrlImageBrowerControllerDelegate
- (UIView*)STPhotoSystemBrowserControllerDidScrollToIndexpath:(NSIndexPath*)indexPath model:(STUrlPhotoModel*)model{
    return self.iconButton;
}
- (void)rightBarActionFromController:(STPhotoUrlImageBrowerController*)controller currentIndexPath:(NSIndexPath *)curentIndexpath{
    
    STActionSheet * actionSheet = [[STActionSheet alloc] initWithTitle:nil
                                                          buttonTitles:@[@"拍照",@"从手机相册选择",@"保存图片"] cancelTitle:@"取消"
                                                              delegate:self
                                   ];
    [actionSheet show];
}
#pragma mark --STActionSheetDelegate
- (void)actionSheet:(STActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        [self.pickerVC showTakePhotoImagePicker:^(UIImage *image) {
            [self sendIconChangeRequestWithImage:image];
        }];
    }
    if (buttonIndex == 1) {
        [self.pickerVC showchosePhotoImagePicker:^(UIImage *image) {
             [self sendIconChangeRequestWithImage:image];
        }];
    }
    if (buttonIndex == 2) {
        [PHPhotoLibrary saveImageToAssetsLibrary:self.iconButton.currentBackgroundImage
                                     libraryName:@"黄金钱包" successHandle:^{
                                         [SVProgressHUD showSuccessWithStatus:@"保存到相册成功"];
                                     } errorHandle:^(STSaveImageError error) {
                                         
                                     }];
    }
}
#pragma mark --NetWork Method
- (void)sendIconChangeRequestWithImage:(UIImage*)image{
    [SVProgressHUD showWithStatus:@"正在更换头像，请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/personal/editPersonal"];
    [[STNetWrokManger defaultClient] imageRequestWithPath:url
                                               parameters:dic
                                                    image:image
                                                imageName:@"head"
                                                 progress:^(NSProgress *progress) {
                                                     
                                                 } success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                     [SVProgressHUD dismiss];
                                                     [self.iconButton setBackgroundImage:image forState:UIControlStateNormal];
                                                     [SVProgressHUD showSuccessWithStatus:@"更换图片成功"];
                                                     self.urlModel.originImage = image;
                                                     [self.pickerVC reloadData];
                                                 } failure:^(NSString *stateCode, STError *error) {
                                                     [SVProgressHUD dismiss];
                                                     [SVProgressHUD showErrorWithStatus:error.desc];
                                                     
                                                 }];
    
}
- (void)sendInfoChangeRequestWithName:(NSString*)name indexPath:(NSIndexPath*)indexPath{
    STTableEasyModel * model = self.dataSouce[indexPath.row];
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    if (name.length) {
        [dic setValue:name forKey:@"nickname"];
    }
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/personal/editPersonal"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 model.detailString = name;
                                                 [SVProgressHUD dismiss];
                                                 [self.tableView reloadData];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendInfoChangeRequestWithProvince:(NSString*)province city:(NSString*)city indexPath:(NSIndexPath*)indexPath{
    STTableEasyModel * model = self.dataSouce[indexPath.row];
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    if (province.length) {
        [dic setValue:province forKey:@"province"];
    }
    if (city.length) {
        [dic setValue:city forKey:@"city"];
    }
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/personal/editPersonal"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 model.detailString = [NSString stringWithFormat:@"%@%@",province,city];
                                                 [SVProgressHUD dismiss];
                                                 [self.tableView reloadData];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendInfoChangeRequestWithGender:(NSString*)gender indexPath:(NSIndexPath*)indexPath{
    STTableEasyModel * model = self.dataSouce[indexPath.row];
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    if (gender.length) {
        NSString * genderIndex = [gender isEqualToString:@"男"]?@"1":@"2";
        [dic setValue:genderIndex forKey:@"gender"];
    }

    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/personal/editPersonal"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 model.detailString = [NSString stringWithFormat:@"%@",gender];
                                                 [SVProgressHUD dismiss];
                                                 [self.tableView reloadData];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end

